//
//  MainViewController.m
//  UI_Contact
//
//  Created by dllo on 15/9/17.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "MainViewController.h"
#import "CoreDataManager.h"
#import "Contacts.h"
#import "DetailViewController.h"
#import "NSString+Characters.h"
#import "AddViewController.h"

@interface MainViewController ()<UITableViewDataSource, UITableViewDelegate, Detail, Add>

@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) CoreDataManager *manager;
@property (nonatomic, retain) NSMutableDictionary *dic;
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) NSMutableArray *arr1;
@property (nonatomic, retain) Contacts *con;

@end

@implementation MainViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
        self.dic = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"All Contacts";
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(opretion:)];

    self.manager = [CoreDataManager defaultManager];
    NSLog(@"%@", [self.manager applicationDocumentsDirectory]);
    [self createTableView];
    [self HandleData];
    
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
//    [button setTitle:@"Edit" forState:UIControlStateNormal];
//    button.frame = CGRectMake(0, 0, 50, 50);
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
//    [button addTarget:self action:@selector(edit:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(edit:)];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSLog(@"songshuang dahaoren ");
}

- (void)edit:(UIBarButtonSystemItem)button
{
    if (self.table.editing == YES) {
        self.table.editing = NO;
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(edit:)];
    }else
    {
    self.table.editing = YES;
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(edit:)];
    }
    
}


- (void)opretion:(UIButton *)button
{

    AddViewController *detail = [[AddViewController alloc]init];
    detail.delegate = self;
    [self.navigationController pushViewController:detail animated:YES];
    
}

- (void)sendValues:(NSString *)name phone:(NSString *)phone
{
    Contacts *con = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:self.manager.managedObjectContext];
    con.name = name;
    con.phone = phone;
    
        [self.manager saveContext];
    [self HandleData];
    
    
}

- (void)HandleData
{
    [self.array removeAllObjects];
    [self.dic removeAllObjects];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Contacts" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:nil];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"group"ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    self.arr = (NSMutableArray *)[self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (self == nil) {
        NSLog(@"%@", error);
    }
    for (Contacts *contact in _arr) {
        NSLog(@"%@", contact.name);
    
    
    
        if ([self.array containsObject:[[contact.name pinyinOfName] firstCharacterOfName]]) {
            NSMutableArray *arr = [self.dic objectForKey:[[contact.name pinyinOfName] firstCharacterOfName]];
            [arr addObject:contact];
            NSLog(@"%ld",arr.count);
            [self.dic setObject:arr forKey:[[contact.name pinyinOfName] firstCharacterOfName]];
        }
        else
        {
            NSMutableArray *arr1 = [NSMutableArray array];
            [arr1 addObject:contact];
            [self.dic setObject:arr1 forKey:[[contact.name pinyinOfName] firstCharacterOfName]];
            self.array = [[self.dic allKeys] sortedArrayUsingSelector:@selector(compare:)].mutableCopy;
        }

        [self.table reloadData];
    }

}




- (void)createTableView
{
    
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:self.table];
    self.table.delegate = self;
    self.table.dataSource = self;
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.array.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [self.array objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return ((NSArray *)[self.dic objectForKey:[self.array objectAtIndex:section]]).count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"];
    }
    NSArray *arr = [self.dic objectForKey:[self.array objectAtIndex:indexPath.section]];
    Contacts *con = [arr objectAtIndex:indexPath.row];
    cell.textLabel.text = [con.name stringByAppendingString:con.phone];
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSMutableArray *arr = [self.dic objectForKey:[self.array objectAtIndex:indexPath.section]];
        [self.manager.managedObjectContext deleteObject:[arr objectAtIndex:indexPath.row]];
        [self.manager saveContext];
//        [arr removeObject:[arr objectAtIndex:indexPath.row]];
        if (arr.count == 0) {
            [self.array removeObject:[self.array objectAtIndex:indexPath.section]];
        }
    }
    [self HandleData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detail = [[DetailViewController alloc]init];
    NSArray *arr = [self.dic objectForKey:[self.array objectAtIndex:indexPath.section]];
//    self.con = [[Contacts alloc]init];
    self.con = [arr objectAtIndex:indexPath.row];
    detail.delegate = self;
    detail.nameStr = _con.name;
    detail.phoneStr = _con.phone;
    [self.navigationController pushViewController:detail animated:YES];
    
}

- (void)updateValues:(NSString *)name phone:(NSString *)phone
{
    
    self.con.name = name;
    self.con.phone = phone;
    [self.manager saveContext];
    [self HandleData];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
